package com.jhy.ws.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jhy.core.helper.LoginHelper;
import com.jhy.core.utils.Check;
import com.jhy.ws.domain.WsMsgRecord;
import com.jhy.ws.domain.vo.WsMsgRecordVo;
import com.jhy.ws.mapper.WsMsgRecordMapper;
import com.jhy.ws.service.IWsMsgRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
@RequiredArgsConstructor
public class WsMsgRecordServiceImpl implements IWsMsgRecordService {

    private final WsMsgRecordMapper recordMapper;

    @Override
    public List<WsMsgRecordVo> findByFriendUserId(Long friendUserId) {
        LambdaQueryWrapper<WsMsgRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w->{
            w.eq(WsMsgRecord::getTargetId, LoginHelper.getUserId())
                    .or()
                    .eq(WsMsgRecord::getTargetId, friendUserId);
        });
        wrapper.and(w->{
            w.eq(WsMsgRecord::getFromUserId, LoginHelper.getUserId())
                    .or()
                    .eq(WsMsgRecord::getFromUserId, friendUserId);
        });
        wrapper.orderByAsc(WsMsgRecord::getMsgId);
        List<WsMsgRecordVo> wsMsgRecordVos = recordMapper.selectVoList(wrapper, WsMsgRecordVo.class);
        if (Check.isNoEmpty(wsMsgRecordVos)){
            for (WsMsgRecordVo item : wsMsgRecordVos) {
                if (item.getFromUserId().equals(LoginHelper.getUserId())){
                    item.setType("sent");
                }else {
                    item.setType("received");
                }
                item.setSendTime(DateUtil.format(item.getCreateTime(), "yyyy-MM-dd HH:mm"));
            }
        }
        return wsMsgRecordVos;
    }
}
